package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import models.Tag;

public class TagDAO {
	
	Connection conexao;

	public TagDAO(Connection openConexaoBanco) {
		this.conexao = openConexaoBanco;
	}

	public boolean cadastrar(Tag tag) {
		boolean retorno = false;
		try {
			String comando = "insert into tag (nome)"
				+ "values(?)";
			
			PreparedStatement p = this.conexao.prepareStatement(comando);
			
			p.setString(1, tag.getNome());
			
			p.execute();
			retorno = true;
			
		} catch (SQLException e) {
			System.out
					.println("Ocorreu erro na hora de inserir o Tag try catch");
			e.printStackTrace();
		}
		return retorno;
	}
	
	public Tag buscarTagPorNome(String nome){
		Tag tag = new Tag();
		
		tag.setNome(nome);
		
		try {
			String comando = "select * from tag where nome='"+nome+"';";
			java.sql.Statement start = conexao.createStatement();
			ResultSet rs = start.executeQuery(comando);
			
			if(rs.first()){
				tag.setId(rs.getInt("id"));
			}
		} catch (Exception e) {

		}
		return tag;
	}

	public List<Tag> listarTags() {
		List<Tag> listaTags = new ArrayList<Tag>();
		
		
		try {
			String comando = "select * from tag";
			java.sql.Statement start = conexao.createStatement();
			ResultSet rs = start.executeQuery(comando);
			
			while(rs.next()){
				Tag tag = new Tag();
				int idTag = Integer.parseInt(rs.getString("id"));
				
				tag.setId(idTag);
				tag.setNome(rs.getString("nome"));
				listaTags.add(tag);
			}
			
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return listaTags;
	}

	public void excluirTag(String _id) {
		String comando = "delete from tag where id=?;";
		try {
			PreparedStatement p = this.conexao.prepareStatement(comando);
			p.setString(1, _id);
			
			p.execute();
		} catch (SQLException e) {
			System.out.println("Ocorreu erro na hora de excluir a TAG try catch");
			e.printStackTrace();
		}
	}

}
